package com.example.backend.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.common.Result;
import com.example.backend.entity.*;
import com.example.backend.mapper.EntityMapper;
import com.example.backend.mapper.EntityRequestMapper;
import com.example.backend.mapper.ProgramMapper;
import com.example.backend.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/entity")
public class EntityController {
    @Value("${server.port}")
    private String port;

    private static final String ip = "http://localhost";
    @Resource
    EntityMapper entityMapper;

    @Resource
    ProgramMapper programMapper;

    @Resource
    EntityRequestMapper entityRequestMapper;

    @PostMapping("/new")
    public Result<?> new_entity(@RequestBody Map<String,Object> data) throws IOException {
        String file = (String) data.get("file");
        String name = (String) data.get("name");
        String userId = (String) data.get("userId");
        String adminId = (String) data.get("adminId");
        Integer requestId = (Integer) data.get("requestId");

        Entity entity = new Entity();
        String originalFilename = name + ".md";  // 获取源文件的名称
        // 定义文件的唯一标识（前缀）
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag + "_" + originalFilename;  // 获取上传的路径
        FileUtil.writeBytes(file.getBytes(),rootFilePath);
        String url = ip + ":" + port + "/files/" + flag;
        entity.setId(null);
        entity.setName(name);
        entity.setPath(url);
        entity.setCommited(true);
        entity.setUserId(userId);
        entity.setAdminId(adminId);
        entityMapper.insert(entity);
        //删除
        EntityRequest temp = new EntityRequest();
        temp.setRequestId(requestId);
        entityRequestMapper.deleteById(temp);
        return Result.success();
    }

    @PostMapping("/not_pass")
    public Result<?> not_pass(@RequestBody EntityRequest entityRequest) throws IOException {
        System.out.println(entityRequest);
        entityRequestMapper.deleteById(entityRequest);
        return Result.success();
    }


    @PostMapping("/search_eq")
    public Result<?> getFiles(@RequestBody Map<String,Object> ob) {
        System.out.println(ob);
//        System.out.println("search_content: " + ob.get("tt"));  //.split("\"")[1]
        Entity entity = entityMapper.selectOne(Wrappers.<Entity>lambdaQuery().eq(Entity::getName,ob.get("search_content")));
        if (entity == null){
            return Result.error("-1","not exist");
        }
        String[] temp = entity.getPath().split("/");
        String flag = temp[temp.length-1];
        String basePath = System.getProperty("user.dir") + "/src/main/resources/files/";  // 定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        String content = "";
        try {
            if (StrUtil.isNotEmpty(fileName)) {
//                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                content = FileUtil.readUtf8String(basePath+fileName);
//                System.out.println(content);
            }
        } catch (Exception e) {
            System.out.println("文件读取失败");
        }
        LambdaQueryWrapper<Program> wrapper = Wrappers.<Program>lambdaQuery().orderByAsc(Program::getParentId);
        wrapper.eq(Program::getParentId,entity.getId());
        List<Program> programs = programMapper.selectList(wrapper);
//        System.out.println(programs);

        ReturnPage res = new ReturnPage();
        res.setEntity(entity);
        res.setPrograms(programs);
        res.setContent(content);
//        System.out.println(res);
        return Result.success(res);
    }

    @PostMapping("/update_entity")
    public Result<?> update_entity( @RequestBody Map<String,Object> data) throws IOException {
        String url = (String) data.get("url");
        String content = (String) data.get("content");

        String[] temp = url.split("/");
        String flag = temp[temp.length-1];
        System.out.println("flag: " + flag);
        String basePath = System.getProperty("user.dir") + "/src/main/resources/files/";  // 定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        System.out.println("filename: "+fileName);
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                System.out.println(basePath+fileName);
                FileUtil.writeBytes(content.getBytes(),basePath+fileName);
            }
            else
            {
                return Result.error("-1","not found");
            }
        } catch (Exception e) {
            System.out.println("文件更新失败");
        }
        return Result.success();
    }
}
